<?php

/**)
 *
 * This class allow you to get Wikipedia PageSource from a downloaded wikipedia dump.
 *
 * In order to parse a big xml file we use xml_parser library.
 * 
 * In order to get the interested article we parse all the TITLE and TEXT markup.
 */

$title;
$text='';
$currentTitle;
$inTitle = FALSE;
$inText = TRUE;
$found = FALSE;
$tmp = FALSE;

function startElement ($parser, $name, $attrs) {
	global $inTitle;
	global $inText;
	global $found;
	
	if ($found) return;
	
	if (0 == strcmp ($name, 'TITLE')) {
		$inTitle = TRUE;
	}
	if (0 == strcmp ($name, 'TEXT')) {
		$inText = TRUE;
	}
}

function endElement ($parser, $name) {
	global $inTitle;
	global $inText;
	global $found;
	global $tmp;
	
	if ($found) return;
	
	if ($inTitle && 0 == strcmp ($name, 'TITLE')) $inTitle = FALSE;
	if ($inText && 0 == strcmp ($name, 'TEXT')) {
		$inTitle = FALSE;
		if ($tmp) $found = TRUE;
	}
}

function characterData ($parser, $data) {
	global $inTitle;
	global $inText;
	global $title;
	global $currentTitle;
	global $found;
	global $text;
	global $tmp;
	
	if ($found) return;
	if ($inTitle) {
		$currentTitle = $data;
	} else if ($inText && 0 == strcmp($title, $currentTitle)) {
		$tmp = TRUE;
		$text .= $data;
	}
}

class wikipediaFileSource implements PageCollection {
	private $language;
	private $xml_parser;
	private $file;
	private $fp;

	public function __construct ($language, $file) {
		$this->language = $language;
		$this->file = $file;
		// Appel à la fonction de création et d'initialisation du parseur
		if (!$this->new_xml_parser ($file)) {die ("Impossible d'ouvrir le document XML");}
	}
    
	public function __destruct () {
		// parser freed
		xml_parser_free ($xml_parser);
	}
    
	public function getLanguage () {
		return $this->language;
	}

	public function getSource ($pageID) {
		global $title;
		global $text;
		global $found;
		$this->title = $pageID;
		$title = $pageID;
    	
		rewind ($this->fp);
		do {
			$data = fread ($this->fp, 4096);			
			if (!xml_parse ($this->xml_parser, $data, feof ($this->fp))) {
				die (sprintf ("XML Error : %s at line %d\n",
					xml_error_string (xml_get_error_code ($this->xml_parser)),
					xml_get_current_line_number ($this->xml_parser))
				);
			}
		} while (!$found);
		$this->text = $text;
		$text = '';
		return $this->text;
	}
    
	public function getRevision ($pageID) {
		return NULL;
	}
    
	function new_xml_parser ($file) {
		$xml_parser = xml_parser_create ();
		xml_parser_set_option ($xml_parser, XML_OPTION_CASE_FOLDING, 1);
		xml_set_element_handler ($xml_parser, 'startElement', 'endElement');
		xml_set_character_data_handler ($xml_parser, 'characterData');
		if (!($fp = @fopen ($file, "r")))
			return FALSE;
		$this->xml_parser = $xml_parser;
		$this->fp = $fp;
		return TRUE;
	}
}
?>
